// import html2canvas from "html2canvas";
import type { EChartsType } from 'echarts';
import dayjs from 'dayjs';
import duration from 'dayjs/plugin/duration';
import { debounce } from 'lodash-es';
import { isArray } from './is';

dayjs.extend(duration);

export function downloadExcel(data: any, title: string = '') {
  const dom = document.createElement('a');
  let blob = new Blob([data], {
    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8',
  });
  dom.style.display = 'none';
  dom.href = URL.createObjectURL(blob);
  dom.download = title;
  document.body.appendChild(dom);
  dom.click();
  document.body.removeChild(dom);
}

export function downloadChartImage(chart: EChartsType, title = '') {
  let picInfo = chart.getDataURL({
    type: 'png',
    pixelRatio: 1,
    backgroundColor: '#ffffff',
  });
  createDownloadLink(picInfo, title);
}

export function base64ToFile(base64: string, fileName = '') {
  let arr = base64.split(',');
  let mime = arr[0].match(/:(.*?);/)?.[1];
  let byteCharacters = atob(arr[1]);
  let byteNumbers = new Array(byteCharacters.length);
  for (let i = 0; i < byteCharacters.length; i++) {
    byteNumbers[i] = byteCharacters.charCodeAt(i);
  }
  let byteArray = new Uint8Array(byteNumbers);
  let file = new File([byteArray], fileName, { type: mime });
  return file;
}

export function createDownloadLink(link: any, title: string) {
  const dom = document.createElement('a');
  dom.style.display = 'none';
  dom.href = link;
  dom.download = title;
  document.body.appendChild(dom);
  dom.click();
  URL.revokeObjectURL(dom.href);
  document.body.removeChild(dom);
}

function createRO(
  cb: (entries?: ResizeObserverEntry[], observer?: ResizeObserver) => any,
  wait: number = 100
) {
  return new ResizeObserver(debounce(cb, wait));
}
/**
 * 监听dom元素大小改变 重绘echarts
 * @param charts
 * @param Dom
 */
export function resize(charts: EChartsType[] | EChartsType, Dom: HTMLElement) {
  if (!isArray(charts)) {
    charts = [charts];
  }
  let observer = createRO(() => {
    (charts as EChartsType[]).forEach(chart => {
      if (chart) {
        chart.resize();
      }
    });
  });
  observer.observe(Dom);
}

export function numberToChinese(num: number): string {
  const digits = '零一二三四五六七八九';
  const units = ['', '十', '百', '千', '万'];
  let result = '';

  // 处理整数部分
  let integerPart = Math.floor(num);
  let integerStr = integerPart.toString();
  for (let i = 0; i < integerStr.length; i++) {
    let digit = Number(integerStr.charAt(i));
    if (digit !== 0) {
      result += digits.charAt(digit) + units[integerStr.length - i - 1];
    } else {
      // 处理零的情况
      if (result.charAt(result.length - 1) !== '零') {
        result += '零';
      }
    }
  }

  // 处理小数部分
  let decimalPart = num - integerPart;
  if (decimalPart > 0) {
    result += '点';
    let decimalStr = decimalPart.toFixed(2).substring(2);
    for (let i = 0; i < decimalStr.length; i++) {
      let digit = Number(decimalStr.charAt(i));
      result += digits.charAt(digit);
    }
  }

  return result;
}
const ONE_DAY = 60 * 60 * 24;
export function formatDuration(paramSecond: number) {
  const duration = dayjs.duration(paramSecond, 'seconds');
  let hours = 0;
  if (paramSecond === ONE_DAY) {
    hours = duration.asHours();
  } else {
    hours = duration.hours();
  }
  const minutes = duration.minutes();
  const seconds = duration.seconds();
  const timeString = `${hours.toString().padStart(2, '0')}:${minutes
    .toString()
    .padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
  return timeString;
}
export function textOverflow(element: HTMLElement) {
  const range = document.createRange();
  range.setStart(element, 0);
  range.setEnd(element, element.childNodes.length);
  const rangeWidth = Math.round(range.getBoundingClientRect().width);
  const computed = window.getComputedStyle(element);
  const padding =
    (parseInt(computed.paddingLeft, 10) || 0) +
    (parseInt(computed.paddingRight, 10) || 0);
  return (
    rangeWidth + padding >= element.offsetWidth ||
    element.scrollWidth > element.offsetWidth
  );
}

export function deCodeArrayBuffer(data: any) {
  const decoder = new TextDecoder('utf-8');
  const text = decoder.decode(data);
  const decodedData = text ? JSON.parse(text) : {};
  return decodedData;
}
